import socket
import threading
import time
import sys

def start_client(client_id):
    # 创建UDP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('0.0.0.0', 0))  # 绑定随机端口
    print(f"{client_id} 启动 0.0.0.0:{sock.getsockname()[1]}")

    # 向服务器注册 127.0.0.1模拟公网服务器公网IP
    server_addr = ('127.0.0.1', 9527)
    sock.sendto(client_id.encode(), server_addr)

    # 接收对方信息
    data, _ = sock.recvfrom(1024)
    peer_id, peer_ip, peer_port = data.decode().split(',')
    peer_addr = (peer_ip, int(peer_port))
    print(f"收到对等方 {peer_id} 地址: {peer_addr}")

    # 打洞
    print("开始打洞...")
    for i in range(5):
        sock.sendto(f"随机发送UDP打洞包 {i} 来自 {client_id}".encode(), peer_addr)
        time.sleep(0.5)

    # 接收消息
    def recv_messages():
        while True:
            data, addr = sock.recvfrom(1024)
            print(f"接收到来自 {addr} 的消息: {data.decode()}")

    # 启动接收线程
    threading.Thread(target=recv_messages, daemon=True).start()

    # 发送消息
    try:
        while True:
            message = input("输入消息内容: ")
            if not message:
                break
            sock.sendto(f"{client_id}: {message}".encode(), peer_addr)
    except KeyboardInterrupt:
        pass

if __name__ == "__main__":

    print(f"入参调用: {sys.argv}")
    start_client(sys.argv[1])